package cn.lg.soar.common.util.listener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * @author luguoxiang
 * @date 2022/4/13
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Lazy(false)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SpringUtils {
    private static ApplicationContext context;
    private static Environment environment;

    public SpringUtils(ApplicationContext applicationContext) {
        context = applicationContext;
        environment = applicationContext.getEnvironment();
    }

    public static <T>T getBean(Class<T> tClass) {
        return context.getBean(tClass);
    }

    public static Object getBean(String name) {
        return context.getBean(name);
    }

    public static <T>T getBean(String name, Class<T> tClass) {
        return context.getBean(name, tClass);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> tClass) {
        return context.getBeansOfType(tClass);
    }

    public static String getProperty(String key) {
        return environment.getProperty(key);
    }

    public static String getProperty(String key, String def) {
        return environment.getProperty(key, def);
    }

    public static <T> T getProperty(String key, Class<T> tClass) {
        return environment.getProperty(key, tClass);
    }

    public static <T> T getProperty(String key, Class<T> tClass, T def){
        return environment.getProperty(key, tClass, def);
    }

    public static ApplicationContext getApiListingContext() {
        return context;
    }

    /**
     * 获取环境
     * @return
     */
    public static Environment getEnvironment() {
        return environment;
    }

    /**
     * 发布事件
     * @param event
     */
    public static void publishEvent(ApplicationEvent event) {
        context.publishEvent(event);
    }

    /**
     * 发布事件
     * @param event
     */
    public static void publishEvent(Object event) {
        context.publishEvent(event);
    }

}
